/**
 * 
 */
package server.user;

import java.util.concurrent.ConcurrentHashMap;

import server.exception.ServerException;

/**
 * Module that manages logged users. 
 * 
 * User Manager module is implemented as a standalone UserManager object. 
 * 
 * @author Kamil Nowak
 *
 */
public class UserManager {

	private final static UserManager instance = new UserManager();
	
	private ConcurrentHashMap<Long,User> users = new ConcurrentHashMap<Long,User>();
	private ConcurrentHashMap<String,User> usersByLogin = new ConcurrentHashMap<String,User>();
	
	private UserManager() {}
	
	/**
	 * Gets standalone instance of EventDispatcher class
	 * @return standalone object
	 */
	public static UserManager instance() {
		return instance;
	}

	/**
	 * Adds a user with a specyfied login and connection id
	 * @param login
	 * @param connectionID
	 * @throws ServerException if such login is already logged in 
	 */
	public void addUser(String login,Long connectionID) throws ServerException {
		
		synchronized (usersByLogin) {
			if (usersByLogin.get(login) != null) throw new ServerException(24);
			
			User user = new User(login,connectionID);
			users.put(connectionID,user);
			usersByLogin.put(login,user);
		}
	}
	
	/**
	 * Gets user with a specyfied connection id
	 * @param connectionId
	 * @return
	 */
	public User getUser(Long connectionId) {
		return users.get(connectionId);
	}

	/**
	 * Removes user from the module.
	 * @param connectionId
	 */
	public void removeUser(Long connectionId) {
		
		User user = users.get(connectionId);
		usersByLogin.remove(user.getLogin());
		users.remove(connectionId);
		
	}

		
}
